package com.gewu.pm.aop;

import android.app.Activity;

import androidx.annotation.NonNull;

import com.gewu.pm.manager.ActivityManager;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.permissions.permission.base.IPermission;
import com.hjq.permissions.permission.PermissionLists;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

import java.util.List;

/**
 *   权限申请切面（已适配XXPermissions 26.5+ 和分区存储）
 */
@Aspect
public class PermissionsAspect {

    /**
     * 方法切入点
     */
    @Pointcut("execution(@com.gewu.pm.aop.Permissions * *(..))")
    public void method() {}

    /**
     * 在连接点进行方法替换
     */
    @Around("method() && @annotation(permissions)")
    public void aroundJoinPoint(final ProceedingJoinPoint joinPoint, Permissions permissions) {
        Activity activity = ActivityManager.getInstance().getTopActivity();
        if (activity == null || activity.isFinishing() || activity.isDestroyed()) {
            return;
        }

        // 使用XXPermissions 26.5+ 新版API
        // 将String数组转换为IPermission并链式调用
        String[] permissionArray = permissions.value();
        XXPermissions permissionRequest = XXPermissions.with(activity);
        for (String perm : permissionArray) {
            // 使用PermissionLists获取对应的IPermission对象
            IPermission iPermission = getPermissionByName(perm);
            if (iPermission != null) {
                permissionRequest.permission(iPermission);
            }
        }
        permissionRequest.request(new OnPermissionCallback() {

                    @Override
                    public void onResult(@NonNull List<IPermission> grantedList, @NonNull List<IPermission> deniedList) {
                        // XXPermissions 26.5+ 只有onResult回调方法
                        boolean allGranted = deniedList.isEmpty();
                        if (allGranted) {
                            try {
                                // 获得权限，执行原方法
                                joinPoint.proceed();
                            } catch (Throwable e) {
                                e.printStackTrace();
                            }
                        }
                        // 权限被拒绝，不执行原方法
                    }
                });
    }

    /**
     * 根据权限名称获取IPermission对象
     * 已适配 Android 13+ 分区存储新权限
     */
    private IPermission getPermissionByName(String permissionName) {
        // 存储权限（分区存储适配）
        if ("android.permission.MANAGE_EXTERNAL_STORAGE".equals(permissionName)) {
            return PermissionLists.getManageExternalStoragePermission();
        } else if ("android.permission.READ_EXTERNAL_STORAGE".equals(permissionName)) {
            return PermissionLists.getReadExternalStoragePermission();
        } else if ("android.permission.WRITE_EXTERNAL_STORAGE".equals(permissionName)) {
            return PermissionLists.getWriteExternalStoragePermission();
        }
        // Android 13+ 新媒体权限
        else if ("android.permission.READ_MEDIA_IMAGES".equals(permissionName)) {
            return PermissionLists.getReadMediaImagesPermission();
        } else if ("android.permission.READ_MEDIA_VIDEO".equals(permissionName)) {
            return PermissionLists.getReadMediaVideoPermission();
        } else if ("android.permission.READ_MEDIA_AUDIO".equals(permissionName)) {
            return PermissionLists.getReadMediaAudioPermission();
        }
        // 相机权限
        else if ("android.permission.CAMERA".equals(permissionName)) {
            return PermissionLists.getCameraPermission();
        }
        // 安装权限
        else if ("android.permission.REQUEST_INSTALL_PACKAGES".equals(permissionName)) {
            return PermissionLists.getRequestInstallPackagesPermission();
        }
        // 定位权限
        else if ("android.permission.ACCESS_FINE_LOCATION".equals(permissionName)) {
            return PermissionLists.getAccessFineLocationPermission();
        } else if ("android.permission.ACCESS_COARSE_LOCATION".equals(permissionName)) {
            return PermissionLists.getAccessCoarseLocationPermission();
        }
        // 电话权限
        else if ("android.permission.CALL_PHONE".equals(permissionName)) {
            return PermissionLists.getCallPhonePermission();
        } else {
            // 对于未明确映射的权限，返回null
            // 注：如需支持更多权限，请在此添加映射
            return null;
        }
    }
}